package com.thingple.web.bridge.printer;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.sdk.bluetooth.android.BluetoothPrinter;
import com.thingple.h5.bridge.AbstractJsBridge;
import com.thingple.h5.bridge.BridgeConfig;
import com.thingple.printert5.PrintHandler;
import com.thingple.printert5.PrintServive;

import java.io.UnsupportedEncodingException;

/**
 *
 * Created by lism on 2017/10/26.
 */
@BridgeConfig(moduleName = "printer")
public class PrinterJsBridgeImpl extends AbstractJsBridge implements PrinterJsBridge {

    public PrinterJsBridgeImpl(WebView webView, Context context) {
        super(webView, context);
    }

    @Override
    public void destroy() {

    }

    @JavascriptInterface
    @Override
    public void print(final String content, final String callbackFunc) {

        if (content == null || callbackFunc == null) {
            return;
        }
        final Handler handler = new Handler();
        final PrintServive printer = new PrintServive();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String error = printer.open();
                if (error == null) {
                    printer.print(new PrintHandler() {
                        @Override
                        public void doPrint(BluetoothPrinter bluetoothPrinter) {
                            try {
                                bluetoothPrinter.send(content.getBytes("GB18030"));
                                printCallback(callbackFunc, "打印完成");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                                printCallback(callbackFunc, "打印机异常:" + e.getMessage());
                            }
                        }
                    });
                    printer.close();
                } else {
                    Log.d(getClass().getName() + "#print", error);
                    printCallback(callbackFunc, error);
                }
            }

            private void printCallback(final String func, final String param) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        final WebView webView = getWebView();
                        webView.post(new Runnable() {
                            @Override
                            public void run() {
                                webView.loadUrl("javascript:" + func + "('" + param + "');");
                            }
                        });
                    }
                });
            }
        }).start();

    }


}
